<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-change="onChange"
      :file-list="fileList"
      :limit="1"
      :class="{disabled: isUploadComplete}"
      :before-upload="beforeUpload"
      :http-request="upload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress :percentage="percentage" style="width: 200px;" />
    <el-dialog title="图片预览" :visible.sync="dialogVisible">
      <el-row type="flex" justify="center" align="middle">
        <img width="500px" :src="dialogImageUrl" alt="">
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
// 指定上传的配置项
// cdn
const cos = new COS({
  SecretId: 'AKIDzqRmqd9QQBftqVtzqQjmeS7WfYAbnjPo',
  SecretKey: '92f15tQgeLlulLegRu70dz4sOdcLnyrU'
})
export default {
  name: 'ImageUpload',
  data() {
    return {
      percentage: 0,
      currentUid: '',
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [
        {
          url: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2.baidu.com%2Fit%2Fu%3D2561548215%2C1690396916%26fm%3D253%26app%3D120%26f%3DJPEG%3Fw%3D800%26h%3D800&refer=http%3A%2F%2Fimg2.baidu.com&app=2002&size=w300&q=a80&n=0&g=0n&fmt=jpeg?sec=1645587467&t=a3812ff6b3e6fbfa239f6e94c976c316'
        }
      ]
    }
  },
  computed: {
    isUploadComplete() {
      return this.fileList.length === 1
    }
  },
  methods: {
    handleRemove(file, fileList) {
      this.fileList = this.fileList.filter(item => !item.uid === file.uid)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    onChange(file, fileList) {
      this.fileList = fileList
    },
    beforeUpload(file) {
      // 要开始做文件上传的检查了
      // 文件类型 文件大小
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
        return false
      }
      //  检查大小
      const maxSize = 5 * 1024 * 1024 // 1M=1024KB 1KB = 1024B
      if (maxSize < file.size) {
        this.$message.error('图片大小最大不能超过5M')
        return false
      }
      // 上传之前记录uid ==> 上传成功之后找到对应uid的这一项，把本地图片链接替换成服务器返回的链接即可 ->
      // 同时打一个标记 upload: true,表示上传完成
      this.currentUid = file.uid
      return true
    },
    upload(params) {
      // 后端完成
      cos.putObject({
        Bucket: 'wuxiaohui-1254415986', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-nanjing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: params.file.name, /* 文件名称，必须字段 */
        StorageClass: 'STANDARD', // 默认选项，不用修改，直接从官网复制基础写法，然后替换自己的用户信息即可
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          // 获取实时的上传进度，赋值给进度条数据
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data.Location)
        if (!err && data.statusCode === 200) {
          console.log('success')
          this.fileList = this.fileList.map(item => {
            if (item.uid === this.currentUid) {
              return {
                ...item,
                url: `http://${data.Location}`,
                upload: true
              }
            }
            return item
          })
        }
      })
    }
  }
}
// 6天课时
// 项目实战 黑马面面 5天
// 26左右
</script>

<style>
.disabled .el-upload--picture-card {
  display: none;
}
</style>
